package com.jlkf.service.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.util.Base64Utils;

public class FatZebraRequestUtils {
	static ResourceBundle rbs = ResourceBundle.getBundle("config/fatZebra", Locale.CHINA);
	private static String Username= rbs.getString("Username");
	private static String Token_Password= rbs.getString("Token_Password");
	static String accountAndPass = Username+":"+Token_Password;//账号密码
	static String encoding = new String(Base64Utils.encode(accountAndPass.getBytes()));//加密的账号密码
	
		public static String sendPost(String url, List<NameValuePair> param, String charset)
				throws Exception {
			CloseableHttpClient client = null;
			StringBuffer result = null;
			try {
				client = HttpClients.createDefault();
				HttpPost post = new HttpPost(url);
				// add header
				post.addHeader("Authorization","Basic "+encoding);
				post.addHeader("Content-Type","application/json");
				post.setEntity(new UrlEncodedFormEntity(param));
				HttpResponse response = client.execute(post);
				BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset));
				result = new StringBuffer();
				String line = "";
				while ((line = rd.readLine()) != null) {
					result.append(line);
				}
				return result.toString();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				client.close();
			}
			return result.toString();
		}
		
		public static String requestPost(String urls,String params) throws IOException, NoSuchAlgorithmException, KeyManagementException {
			  URL url = new URL(urls);
		        HttpsURLConnection conn = null;
		        PrintWriter out = null;
		        BufferedReader in = null;
		        String result = "";
		        conn = (HttpsURLConnection)url.openConnection();
		        SSLContext sc = SSLContext.getInstance("TLSv1.2");
		        sc.init(null, null, new java.security.SecureRandom());
		        conn.setSSLSocketFactory(sc.getSocketFactory());
		        conn.setRequestProperty("accept", "*/*");
		        conn.setRequestProperty("Content-type", "application/json");
		        conn.setRequestProperty("Authorization","Basic "+encoding);
		        conn.setDoOutput(true);
		        conn.setDoInput(true);
		        conn.setUseCaches(false);
		        out = new PrintWriter(conn.getOutputStream());
//		        out.print("{\"card_number\":\"5123456789012346\",\"card_holder\":\"test\",\"card_expiry\":\"05/2023\",\"cvv\":\"123\"}");
		        out.println(params);
		        out.flush();
		        in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
		        String line;
		        while ((line = in.readLine()) != null) {
		            result += line;
		        }
		        System.out.print(result);
				return result;
		}
		
		
		public static void main(String[] args) {
			String param = "{\"card_token\":\"n30gjpbd\",\"card_holder\":\"test\",\"cvv\":\"123\"," + "\"amount\":100,\"customer_ip\":\"101.101.101.101\"," + "\"currency\":\"AUD\",\"reference\":\"FAB201801040003\"}";
			try {
				System.out.println(FatZebraRequestUtils.requestPost("https://gateway.sandbox.fatzebra.com.au/v1.0/purchases", param));
			} catch (KeyManagementException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
}
